package com.csu.letaobackend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.csu.letaobackend.bean.*;
import com.csu.letaobackend.commom.CommonResponse;
import com.csu.letaobackend.commom.SnowFlake;
import com.csu.letaobackend.persistence.*;
import com.csu.letaobackend.service.CartService;
import com.csu.letaobackend.vo.CartItemVO;
import com.csu.letaobackend.vo.OrderItemVO;
import com.csu.letaobackend.vo.OrderVO;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@MapperScan("com.csu.letaobackend.persistence")
public class CartServiceImpl implements CartService {

      @Autowired
      ItemDao itemDao;

      @Autowired
      CartItemDao cartItemDao;

      @Autowired
      PictureDao pictureDao;

      @Autowired
      OrderDao orderDao;

      @Autowired
      OrderItemDao orderItemDao;

      @Autowired
      ShopDao shopDao;

      @Autowired
      ReceivingDao recevingDao;

      @Autowired
      SpecialofferDao specialofferDao;

      @Autowired
      CouponDao couponDao;

      @Autowired
      ReceivingDao receivingDao;

      @Autowired
      RefundserviceDao refundserviceDao;



      @Override
      public CommonResponse<List<CartItemVO>> getCartitemListByUsername(String username) {
            List<CartItemVO> cartItemVOList = new ArrayList<>();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            System.out.println(username);
            List<CartItem> cartItemList = cartItemDao.selectList(queryWrapper);
            for (CartItem cartItem : cartItemList) {
                  cartItemVOList.add(entityToVO(cartItem));
            }
            return CommonResponse.createForSuccess(cartItemVOList);
      }

      @Override
      public CommonResponse getCartitemNum(String username) {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            List<CartItem> cartItemList = cartItemDao.selectList(queryWrapper);
            return CommonResponse.createForSuccess(cartItemList.size());
      }

      @Override
      public CommonResponse<List<CartItemVO>> addCartitem(int itemid, int num, double price, String attrdescription, String username) {

            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("username", username);
            updateWrapper.eq("itemid", itemid);

            if (cartItemDao.selectOne(updateWrapper) != null) {//购物车已经有
                  num += cartItemDao.selectOne(updateWrapper).getNum();
                  updateWrapper.set("num", num);
                  if (!checkStock(itemid, num))
                        return CommonResponse.createForError("库存不足");

                  updateWrapper.set("newprice", price);
                  updateWrapper.set("attrdescription", attrdescription);
                  cartItemDao.update(null, updateWrapper);
                  return CommonResponse.createForSuccessMessage("修改成功");
            } else {//购物车没有 插入元组
                  if (!checkStock(itemid, num))
                        return CommonResponse.createForError("库存不足");
                  CartItem cartItem = new CartItem();
                  cartItem.setItemid(itemid);
                  cartItem.setShopid(itemDao.selectById(itemid).getShopid());
                  cartItem.setUsername(username);
                  cartItem.setNum(num);
                  cartItem.setNewprice(price);
                  cartItem.setAttrdescription(attrdescription);
                  cartItemDao.insert(cartItem);
                  return CommonResponse.createForSuccessMessage("插入成功");
            }
      }

      @Override
      public CommonResponse<List<CartItemVO>> updateCartitem(int itemid, int num, double price, String attrdescription, String username) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("username", username);
            updateWrapper.eq("itemid", itemid);

            if (!checkStock(itemid, num))
                  return CommonResponse.createForError();

            updateWrapper.set("num", num);
            updateWrapper.set("newprice", price);
            updateWrapper.set("attrdescription", attrdescription);
            cartItemDao.update(null, updateWrapper);
            return CommonResponse.createForSuccessMessage("修改成功");
      }


      @Override
      public CommonResponse<List<CartItemVO>> deleteCartitem(int itemid, String username) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("username", username);
            updateWrapper.eq("itemid", itemid);
            cartItemDao.delete(updateWrapper);
            return CommonResponse.createForSuccessMessage("删除成功");
      }

      @Override
      public CommonResponse<List<OrderVO>> createOrders(String username, int recevingid,List<Integer> couponids) {
            System.out.println(username);
            List<OrderVO> orderVOList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            List<CartItem> cartItemList = cartItemDao.selectList(queryWrapper);
            List<Integer> shopidList = new ArrayList();
            for (CartItem cartItem : cartItemList) {
                  if (!shopidList.contains(cartItem.getShopid()))
                        shopidList.add(cartItem.getShopid());
            }

            for (int shopid : shopidList) {
                  QueryWrapper queryWrapper1 = new QueryWrapper();
                  queryWrapper1.eq("username", username);
                  queryWrapper1.eq("shopid", shopid);
                  cartItemList = cartItemDao.selectList(queryWrapper1);
                  String orderId = SnowFlake.createOrderId();
                  //  插入order 表
                  Order order = new Order();
                  order.setOrderid(orderId);
                  order.setShopid(shopid);
                  order.setUsername(username);
                  order.setRecevingid(recevingid);
                  order.setStatus(0);
                  order.setOrdertime(new Date());
                  order.setRecevingtime(new Date(System.currentTimeMillis() + 259200000));
                  order.setIsevaluate(0);
                  order.setIspay(0);

                  order.setCouponid(0);//默认为0
                  //统计优惠券的使用
                  for(int couponid:couponids){
                        Coupon tmp = couponDao.selectById(couponid);
                        if(tmp==null)continue;
                        if(tmp.getShopid()==shopid)
                              order.setCouponid(couponid);
                  }
                  orderDao.insert(order);

                  //  遍历cartItemList 放入 orderItem表
                  for (CartItem cartItem : cartItemList) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setOrderid(orderId);
                        orderItem.setItemid(cartItem.getItemid());
                        orderItem.setNum(cartItem.getNum());
                        orderItem.setNewprice(cartItem.getNewprice());
                        orderItem.setAttrdescription(cartItem.getAttrdescription());
                        orderItemDao.insert(orderItem);
                  }
                  orderVOList.add(entityToVO(order));

            }
            //购物车内商品清除
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", username);
            int res = cartItemDao.deleteByMap(map);
            System.out.println(res);
            return CommonResponse.createForSuccess(orderVOList);
      }

      public Boolean checkStock(int itemid, int neednum) {
            Item item = itemDao.selectById(itemid);
            if (item.getStock() >= neednum)
                  return true;
            else
                  return false;
      }

      private CartItemVO entityToVO(CartItem cartItem) {
            Picture picture = pictureDao.selectById(itemDao.selectById(cartItem.getItemid()).getPictureid());
            Item item = itemDao.selectById(cartItem.getItemid());
            CartItemVO cartItemVO = new CartItemVO();
            cartItemVO.setUsername(cartItem.getUsername());
            cartItemVO.setShopid(cartItem.getShopid());
            cartItemVO.setShopname(shopDao.selectById(cartItem.getShopid()).getName());
            cartItemVO.setItemid(cartItem.getItemid());
            cartItemVO.setDescription(item.getDescription());
            cartItemVO.setNum(cartItem.getNum());
            if (specialofferDao.selectById(cartItem.getItemid()) != null)
                  cartItemVO.setSpecialrate(specialofferDao.selectById(cartItem.getItemid()).getRate());
            else
                  cartItemVO.setSpecialrate(1);
            cartItemVO.setPrice(cartItem.getNewprice());
            cartItemVO.setAllprice(cartItem.getNewprice() * cartItem.getNum());
            cartItemVO.setAttrdescription(cartItem.getAttrdescription());
            cartItemVO.setSrc(picture.getSrc());

            return cartItemVO;
      }

      private OrderVO entityToVO(Order order) {
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderid(order.getOrderid());
            orderVO.setShopid(order.getShopid());
            orderVO.setUsername(order.getUsername());
            orderVO.setShopname(shopDao.selectById(order.getShopid()).getName());
            orderVO.setRecevingid(order.getRecevingid());
            orderVO.setStatus(order.getStatus());
            orderVO.setRecevingtime(order.getRecevingtime());
            orderVO.setOrdertime(order.getOrdertime());
            orderVO.setIsevaluate(order.getIsevaluate());
            orderVO.setIspay(order.getIspay());

            //收货信息设置
            Receiving receving = receivingDao.selectById(order.getRecevingid());
            orderVO.setReceivingaddr(receving.getAddrcoutry() + receving.getAddrprovince() + receving.getAddrcouty() + receving.getAddrdetails());
            orderVO.setContactphone(receving.getContactphone());
            orderVO.setRecivename(receving.getReceivename());

            //加入orderitem列表
            List<OrderItemVO> orderItemVOList = new ArrayList<>();
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("orderid", order.getOrderid());
            List<OrderItem> orderItemList = orderItemDao.selectList(updateWrapper);
            for (OrderItem orderitem : orderItemList) {
                  orderItemVOList.add(entityToVO(orderitem));
            }
            orderVO.setOrderItemVOList(orderItemVOList);
            orderVO.setCouponid(order.getCouponid());
            //设置coupondiscount
            if(order.getCouponid()==0)
                  orderVO.setCoupondiscount(0);
            else {
                  double discount = couponDao.selectById(order.getCouponid()).getDiscount();
                  orderVO.setCoupondiscount(discount);
            }

            double ordertotal=0; //订单总价
            double orderdiscount=0;  //订单总优惠
            for(OrderItemVO orderItemVO:orderItemVOList){
                  ordertotal+=orderItemVO.getAllprice();
                  orderdiscount+=orderItemVO.getDiscount();
            }
            orderVO.setOrdertotal(ordertotal);
            orderVO.setOrderdiscount(orderdiscount);
            double actualpay=ordertotal-orderdiscount-orderVO.getCoupondiscount(); //实际支付
            orderVO.setActualpay(actualpay);

            if(refundserviceDao.selectOne(updateWrapper)==null)
                  orderVO.setServiceid(0);
            else
                  orderVO.setServiceid(refundserviceDao.selectOne(updateWrapper).getServiceid());
            return orderVO;
      }

      private OrderItemVO entityToVO(OrderItem orderitem) {
            Picture picture = pictureDao.selectById(orderitem.getItemid());
            Item item = itemDao.selectById(orderitem.getItemid());
            OrderItemVO orderitemVO = new OrderItemVO();
            orderitemVO.setOrderid(orderitem.getOrderid());
            orderitemVO.setItemid(orderitem.getItemid());
            orderitemVO.setDescription(item.getDescription());
            orderitemVO.setNum(orderitem.getNum());
            orderitemVO.setPrice(orderitem.getNewprice());
            orderitemVO.setAllprice(orderitem.getNewprice() * orderitem.getNum());
            orderitemVO.setAttrdescription(orderitem.getAttrdescription());
            orderitemVO.setSrc(picture.getSrc());

            if (specialofferDao.selectById(orderitem.getItemid()) != null)
                  orderitemVO.setSpecialrate(specialofferDao.selectById(orderitem.getItemid()).getRate());
            else
                  orderitemVO.setSpecialrate(1);
            orderitemVO.setDiscount(orderitem.getNewprice()* orderitem.getNum()*(1-orderitemVO.getSpecialrate()));
            return orderitemVO;
      }
}
